import { messages } from "share/common";
import React from "react";
import { connect } from "react-redux";
import {
  Form,
  Input,
  Switch,
  Button,
  Icon,
  Select,
  message,
  Spin,
  Tooltip,
} from "antd";
import config from "config";
import httpFetch from "share/httpFetch";
import "styles/receipt-type-setting/contract-type-define/new-contract-type.scss";
import { Chooser } from "components/index";
import service from "./service";
import { getCycleSearchItem, getClassifyTypeSearchItem } from "./config";
import errorMessage from "share/errorMessage";

const FormItem = Form.Item;
const { Option } = Select;

class ExpenseAmountNewForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      fetching: false,
      isEnabled: true,
      setOfBooksOptions: [],
      contractCategory: [],
      data: {},
      formTypeOptions: [],
      radioValue: "all",
      showSelectEmployeeGroup: false,
      chosenEmployeeIDs: [],
      editTag: false,
      // 适用人员
      applyEmployee: "BASIS_01",
      departmentOrUserGroupIdList: [],
      permissions: {
        type: "all",
        values: [],
      },
    };
  }

  componentDidMount() {
    // this.setState({ data: props.data });
  }

  componentWillReceiveProps(nextprops) {
    if (nextprops.params.show && !this.props.params.show) {
      this.props.form.resetFields();
    }
  }

  onFormFocus = () => {
    this.getFormType();
  };

  // 获取关联表单类型
  getFormType = () => {
    this.setState({ fetching: true });
    let setOfBooksId =
      this.state.data.setOfBooksId || this.props.params.setOfBooksId;
    if (!setOfBooksId) {
      setOfBooksId = 0;
    }
    httpFetch
      .get(
        `${config.baseUrl}/api/custom/forms/loan/reference?setOfBooksId=${setOfBooksId}`
      )
      .then((res) => {
        this.setState({ formTypeOptions: res.data, fetching: false });
      });
  };

  // 新建保存
  handleSave = (e) => {
    e.preventDefault();
    this.setState({ loading: true });
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      if (err) {
        this.setState({ loading: false })
        return;
      }
      values.isEnabled = this.state.isEnabled;
      const { cycle, expenseTypeOid, classifyType } = values;

      try {
        const res = await service.saveQuato({
          cycle: parseInt(cycle, 10),
          expenseTypeOid: expenseTypeOid[0].expenseTypeOID,
          classifyType: parseInt(classifyType, 10),
        });
        if (res.status === 200) {
          this.setState({ loading: false });
          message.success(messages("common.save.success", { name: "" }));
          const shouldRefresh = true;
          this.props.close(shouldRefresh);
        }
      } catch (e) {
        this.setState({ loading: false });
        if (e.response) {
          errorMessage(e.response);
          return;
        }
        message.error(e.message);
        message.error(`${messages("common.save.filed")}`);
      }
    });
  };

  // 取消
  handleCancel = () => {
    this.props.form.resetFields();
    const shouldRefresh = false;
    this.props.close(shouldRefresh);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { params } = this.props;
    const { loading } = this.state;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 10, offset: 1 },
    };

    return (
      <div className="new-contract-type">
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label="费用类型">
            {getFieldDecorator("expenseTypeOid", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.select"),
                },
              ],
            })(
              <Chooser
                {...{
                  type: "selectInvoiceType",
                  // listType: 'invoice_budget',
                  options: [],
                  valueKey: "expenseTypeOID",
                  labelKey: "name",
                  listExtraParams: {
                    enabled: true,
                    setOfBooksId: params.setOfBooksId,
                    subsidyType: 0,
                    isQuato: 1
                  },
                  single: true,
                  id: "expenseTypeOid",
                  label: messages("budget-setting.key85" /* 费用类型 */),
                }}
              />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="分类">
            {getFieldDecorator("classifyType", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.select"),
                },
              ],
              initialValue: "1",
            })(
              <Select>
                {getClassifyTypeSearchItem().options.map((option) => (
                  <Option key={option.value}>{option.label}</Option>
                ))}
              </Select>
            )}
          </FormItem>

          <FormItem {...formItemLayout} label="周期">
            {getFieldDecorator("cycle", {
              rules: [
                {
                  required: true,
                  message: messages("common.please.select"),
                },
              ],
              initialValue: "1",
            })(
              <Select>
                {getCycleSearchItem().options.map((option) => (
                  <Option key={option.value}>{option.label}</Option>
                ))}
              </Select>
            )}
          </FormItem>

          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>
              {messages("common.save")}
            </Button>
            <Button onClick={this.handleCancel}>
              {messages("common.cancel")}
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

ExpenseAmountNewForm.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    main: state.main,
  };
}

const wrappedExpenseAmountNewForm = Form.create()(ExpenseAmountNewForm);

export default connect(mapStateToProps, null, null, { withRef: true })(
  wrappedExpenseAmountNewForm
);
